<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Config extends Backend
{
    public function index()
    {

        $ConfigList = model('Config')->select();

        if ($this->request->isPost()) {
            $params = $this->request->param();

            $list = model('Config')->column('key,id');

            $ConfigData = [];

            foreach ($params as $key => $item) {
                $id = isset($list[$key]) ? $list[$key] : 0;
                $ConfigData[] = [
                    'id' => $id,
                    "value" => $item
                ];
            }

            $idArr = [];
            $files[] = [];

            if (!empty($_FILES)) {
                foreach ($_FILES as $key => $item) {
                    // halt($key);
                    //上传不成功或者没有图片
                    if ($_FILES[$key]['error'] != 0 || $_FILES[$key]['size'] <= 0) {
                        continue;
                    }

                    $file = upload($key);
                    $files = $file;
                    if ($file) {
                        // halt($file);
                        $id = isset($list[$key]) ? $list[$key] : 0;
                        if ($id) {
                            $idArr[] = $id;
                            $ConfigData[] = [
                                'id' => $id,
                                'value' => $file['data']
                            ];
                        }
                    }
                }
            }
            // halt($ConfigData);
            $ConfigThumbs = model('Config')->whereIn('id', $idArr)->select();
            $result = model('Config')->isUpdate(true)->saveAll($ConfigData);
            if ($result === FALSE) {
                if (!empty($_FILES) && !empty($files)) {
                    foreach ($files as $item) {
                        @is_file('.' . $item['data']) && @unlink('.' . $item['data']);
                    }
                }
                $this->error(model('Config')->getError());
            } else {
                if (!empty($_FILES) && !empty($ConfigThumbs)) {
                    // halt($ConfigThumbs);
                    foreach ($ConfigThumbs as $item) {
                        @is_file('.' . $item['value']) && @unlink('.' . $item['value']);
                    }
                }
                $this->success('更新网站配置成功', url('admin/config/index'));
            }
        }
        $navTitle = '网站配置';

        return $this->fetch('', [
            'navTitle' => $navTitle,
            'ConfigList' => $ConfigList
        ]);
    }
}
